package com.stars.easyms.logger.support.logback.pattern.converter;

import ch.qos.logback.classic.pattern.*;
import ch.qos.logback.classic.spi.ILoggingEvent;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>className: EasyMsNamedConverter</p>
 * <p>description: EasyMs自定义NamedConverter类，增加缓存</p>
 *
 * @author guoguifang
 * @date 2019-10-22 18:11
 * @since 1.3.3
 */
public final class EasyMsNamedConverter extends ClassicConverter {

    private static final int MAX_CACHE_SIZE = 256;

    private static final Map<String, String> ABBR_NAME_CACHE = new HashMap<>(MAX_CACHE_SIZE);

    private Abbreviator abbreviator;

    @Override
    public void start() {
        String optStr = getFirstOption();
        if (optStr != null) {
            try {
                int targetLen = Integer.parseInt(optStr);
                if (targetLen == 0) {
                    abbreviator = new ClassNameOnlyAbbreviator();
                } else if (targetLen > 0) {
                    abbreviator = new TargetLengthBasedClassNameAbbreviator(targetLen);
                }
            } catch (NumberFormatException nfe) {
                // ignore
            }
        }
    }

    @Override
    public String convert(ILoggingEvent event) {
        String fqn = event.getLoggerName();
        if (abbreviator == null) {
            return fqn;
        } else {
            if (ABBR_NAME_CACHE.size() > MAX_CACHE_SIZE) {
                ABBR_NAME_CACHE.clear();
            }
            return ABBR_NAME_CACHE.computeIfAbsent(fqn, key -> abbreviator.abbreviate(key));
        }
    }

}